package com.example.tool.conf;//package com.example.tool.conf;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.tool.bean.business.WarehouseConfigEntity;
import com.example.tool.bean.business.WarehouseInterceptionConfig;
import com.example.tool.bean.business.wdt.SelfOrderDO;
import com.example.tool.erp.sdk.api.sales.dto.TradeQueryResponse;
import com.example.tool.service.AsyncService;
import com.example.tool.service.RedisService;
import com.example.tool.service.selforder.SelfOrderService;
import com.example.tool.util.DDUtil;
import com.example.tool.util.ExpressDeliveryUtil.ExpressDeliveryUtil;
import com.example.tool.util.WDTUtil;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.example.tool.util.ExpressDeliveryUtil.ExpressDeliveryUtil.judgeExpressDeliveryType;

/**
 * 仓库群 发货超时 揽收超时
 */
@Component
public class SelfOrderMonitorCollectTasks {
    @Autowired
    private RedisService redisService;
    @Autowired
    private AsyncService asyncService;
    @Qualifier("selfOrderService")
    @Autowired
    private SelfOrderService selfOrderService;
    private static final String ddLinkUrl = "https://alidocs.dingtalk.com/i/nodes/%s";
    private static final String qwLinkUrl = "https://doc.weixin.qq.com/smartsheet/%s";
    private static final String keyTemplate = "sys:sendOrderWorkbookId:%s:%s";
    private static final String deliveryTimeoutRangeAddressTemplate = "A%s:E%s";//发货
    private static final String deliveryTimeoutMsgTitle = "发货超时预警通知-测试阶段";
    private static final List<String> deliveryTimeoutHeaderValues = Arrays.asList("原始单号", "出库单号", "订单编号", "物流单号", "最晚发货时间");
    private static final String deliveryTimeoutMsgTemplate = "原始单号：%s\n出库单号：%s\n订单编号：%s\n物流单号：%s\n最晚发货时间：%s";
    private static final String deliveryTimeoutEndingContent = "订单类型：订单即将发货超时，请优先处理，并回传发货成功状态。";
    private static final String collectionDelayRangeAddressTemplate = "A%s:E%s";//揽收
    private static final String collectionDelayMsgTitle = "揽收超时预警通知-测试阶段";
    private static final List<String> collectionDelayHeaderValues = Arrays.asList("原始单号", "出库单号", "订单编号", "物流单号", "发货时间");
    private static final String collectionDelayMsgTemplate = "原始单号：%s\n出库单号：%s\n订单编号：%s\n物流单号：%s\n发货时间：%s";
    private static final String collectionDelayEndingContent = "订单类型：订单已发货未揽收，揽收即将超时，请优先处理揽收，并回传揽收成功记录。";
    //已审核未发货
    private List<Integer> findDropshippingStatus = Arrays.asList(16, 19, 20, 21, 23, 24, 25, 27, 30, 35, 40);
    //已发货
    private List<Integer> findShippedStatus = Arrays.asList(95, 96, 101, 110);
    //代发货和已发货
    private List<Integer> allFindShippedStatus = Arrays.asList(16, 19, 20, 21, 23, 24, 25, 27, 30, 35, 40, 55, 95, 96, 101, 110);
    private static final Integer readBatchSize = 3000;
    private static final Integer updateBatchSize = 3000;
    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static final SimpleDateFormat sdfYYYYMMdd = new SimpleDateFormat("yyyy-MM-dd");
    private static final SimpleDateFormat sdfYYYYMM = new SimpleDateFormat("yyyy-MM");
    //保存时间值
    private static final Integer dataSaveDays = 7;
    //保存时间的单位
    private static final TimeUnit timeUnit = TimeUnit.DAYS;
    //常温
    private static final String roomTemperatureType = "1";
    //冻品
    private static final String frozenProductsType = "2";
    //发货超时
    private static HashMap<String, WarehouseConfigEntity> WAREHOUSE_INTERCEPT_CONFIG = new HashMap<>();

    static {//发货超时
        WAREHOUSE_INTERCEPT_CONFIG.put(WarehouseConfEnum.LG_CW.getCode(), //苍南-龙港（常温仓）
                new WarehouseConfigEntity(WarehouseConfEnum.LG_CW.getRoomTemperatureType(), //常温
                        new WarehouseInterceptionConfig(//龙港仓（常温）审单对接群
                                "kDnRL6jAJMDAYjEwHDvX1PKNVyMoPYe1",
                                WarehouseMsgSDConfEnum.LG_CW_SD.getSecret(),
                                WarehouseMsgSDConfEnum.LG_CW_SD.getToken(),
//            "SEC19af71dcdb6f679f375de58a69a74dd66d723df30ea6bd6e5fd3d2aba86e8208",
//            "80e2322d737f724c603f6157168246ab6883e0713cc705646bb52d336b6df3e3",
                                null, null)
                        ,
         /*           Arrays.asList(
            new WarehouseExpressDeliveryConfig(//龙港仓（常温）快递售后群（申通）
                    WarehouseMsgKDConfEnum.LG_CW_KD_SOT.getExpressDeliveryType(),
                    WarehouseMsgKDConfEnum.LG_CW_KD_SOT.getPlatform(),
//             UNKNOWN,
//            1,
            "ZgpG2NdyVXaOEALjT3q05z94JMwvDqPk",
                    WarehouseMsgKDConfEnum.LG_CW_KD_SOT.getSecret(),
                    WarehouseMsgKDConfEnum.LG_CW_KD_SOT.getToken(),
//            "SEC19af71dcdb6f679f375de58a69a74dd66d723df30ea6bd6e5fd3d2aba86e8208",
//            "80e2322d737f724c603f6157168246ab6883e0713cc705646bb52d336b6df3e3",

                    null,null)
            )*/null
                )
        );


        WAREHOUSE_INTERCEPT_CONFIG.put(WarehouseConfEnum.CQ_DP.getCode(), //重庆-中通（冻品仓）
                new WarehouseConfigEntity(WarehouseConfEnum.CQ_DP.getRoomTemperatureType(), //冻品
                        new WarehouseInterceptionConfig(//重庆仓（冻品）审单对接群
                                "jb9Y4gmKWrblnwA4UaXja56mWGXn6lpz",
                                WarehouseMsgSDConfEnum.CQ_DP_SD.getSecret(),
                                WarehouseMsgSDConfEnum.CQ_DP_SD.getToken(),
//                    "SEC5c0852177e757940afaaecad5fd0ddd55f653c299bad9a6d5204e81752788afe",
//            "b665f561ffd7755dfb003b82d2446b6e5ddafecc3b213e4db8a04da9799b3067",

                                null, null),
          /*  Collections.singletonList(new WarehouseExpressDeliveryConfig(//重庆仓（冻品）快递售后群
            WarehouseMsgKDConfEnum.CQ_DP_KD.getExpressDeliveryType(),
            WarehouseMsgKDConfEnum.CQ_DP_KD.getPlatform(),
//            UNKNOWN,
//            1,
            "6LeBq413JAeGXx0mFnZxLNMMJDOnGvpb",
                    WarehouseMsgKDConfEnum.CQ_DP_KD.getSecret(),
                    WarehouseMsgKDConfEnum.CQ_DP_KD.getToken(),
//            "SEC5c0852177e757940afaaecad5fd0ddd55f653c299bad9a6d5204e81752788afe",
//            "b665f561ffd7755dfb003b82d2446b6e5ddafecc3b213e4db8a04da9799b3067",
                    null,null))*/
                        null
                )
        );

        WAREHOUSE_INTERCEPT_CONFIG.put(WarehouseConfEnum.JG_CW.getCode(), //广州-江高（常温仓）
                new WarehouseConfigEntity(WarehouseConfEnum.JG_CW.getRoomTemperatureType(),//常温
                        new WarehouseInterceptionConfig(//江高仓（常温）审单对接群
                                "Obva6QBXJw6lYwAMFlx2ADLyVn4qY5Pr",
                                WarehouseMsgSDConfEnum.JG_CW_SD.getSecret(),
                                WarehouseMsgSDConfEnum.JG_CW_SD.getToken(),
//            "SEC71886d7de0e913186f1c34b796a5f8381b29537f327d3da2977b24d590c69a54",
//            "939653f7533235b20bb6f47b49517587c43c838f78de8f776e041f07eefdd8b3",

                                null, null),
           /* Arrays.asList(new WarehouseExpressDeliveryConfig(//江高仓（常温）快递售后群（圆通）
//            UNKNOWN,
//            1,
                WarehouseMsgKDConfEnum.JG_CW_KD_JT.getExpressDeliveryType(),
                WarehouseMsgKDConfEnum.JG_CW_KD_JT.getPlatform(),
            "EpGBa2Lm8ajvKoMmIZ0PRP7QWgN7R35y",
                            WarehouseMsgKDConfEnum.JG_CW_KD_JT.getSecret(),
                            WarehouseMsgKDConfEnum.JG_CW_KD_JT.getToken(),
//            "SEC71886d7de0e913186f1c34b796a5f8381b29537f327d3da2977b24d590c69a54",
//            "939653f7533235b20bb6f47b49517587c43c838f78de8f776e041f07eefdd8b3",
                            null,null))*/
                        null
                ));

        WAREHOUSE_INTERCEPT_CONFIG.put(WarehouseConfEnum.HF_DP.getCode(), //合肥-肥西（冻品仓）
                new WarehouseConfigEntity(WarehouseConfEnum.HF_DP.getRoomTemperatureType(),//冻品
                        new WarehouseInterceptionConfig(//合肥仓（冻品）审单对接群
                                "93NwLYZXWybly4ANUv6NR2vKVkyEqBQm",
                                WarehouseMsgSDConfEnum.HF_DP_SD.getSecret(),
                                WarehouseMsgSDConfEnum.HF_DP_SD.getToken(),
//            "SECa00b70bcf2d9e339d899e4449b8e95ffbfe042759b7c83294f1e70a5476d4c1b",
//            "46653a24eda213db1d93fa75b78a865b702f8c7d662345089d7dee66a58ddde5",
                                null, null),
       /*     Arrays.asList(new WarehouseExpressDeliveryConfig(//台肥仓（冻品）快递售后群（统一）
            ExpressDeliveryUtil.UNKNOWN,
            1,
            "YQBnd5ExVE1mZxG0Tk754Q1bVyeZqMmz",
            "SECa00b70bcf2d9e339d899e4449b8e95ffbfe042759b7c83294f1e70a5476d4c1b",
            "46653a24eda213db1d93fa75b78a865b702f8c7d662345089d7dee66a58ddde5",null,null))*/
                        null
                ));

        WAREHOUSE_INTERCEPT_CONFIG.put(WarehouseConfEnum.TZ_DP.getCode(), //济南-天泽（冻品仓）
                new WarehouseConfigEntity(WarehouseConfEnum.TZ_DP.getRoomTemperatureType(), //冻品
                        new WarehouseInterceptionConfig(//天泽仓（冻品）审单对接群
                                "o14dA3GK8gzNMZ2YF91e9B36J9ekBD76",
                                WarehouseMsgSDConfEnum.TZ_DP_SD.getSecret(),
                                WarehouseMsgSDConfEnum.TZ_DP_SD.getToken(),
//            "SEC02bc013b8a145ac6f7eec43b7e75eeafb9267af06105c2d33572a49a6a9594f7",
//            "e827de0a3c7c23763b7aa34e5a2750bd9d48e8a01fdd10e658eb674b11ef3bfb",
                                null, null),
            /*Arrays.asList(new WarehouseExpressDeliveryConfig(//天泽仓（冻品）快递售后群（统一）
            ExpressDeliveryUtil.UNKNOWN,
            1,
            "7NkDwLng8ZK3GnEkTjzRwNP7WKMEvZBY",
            "SEC02bc013b8a145ac6f7eec43b7e75eeafb9267af06105c2d33572a49a6a9594f7",
            "e827de0a3c7c23763b7aa34e5a2750bd9d48e8a01fdd10e658eb674b11ef3bfb",null,null) )*/
                        null
                ));

        WAREHOUSE_INTERCEPT_CONFIG.put(WarehouseConfEnum.SH_DP.getCode(), //上海-上海（冻品仓）
                new WarehouseConfigEntity(WarehouseConfEnum.SH_DP.getRoomTemperatureType(), //冻品
                        new WarehouseInterceptionConfig(//上海仓 （冻品）审单对接群
                                "KGZLxjv9VGdRm4EYC7vZM7m3J6EDybno",
                                WarehouseMsgSDConfEnum.SH_DP_SD.getSecret(),
                                WarehouseMsgSDConfEnum.SH_DP_SD.getToken(),

//            "SEC0c1e7682f88bb4cb7166ecd3fe715ae005a626ef41595d04af62d069910e9d23",
//            "f608f1d572bb78926f993125aaa8d84b6d49f1c5df50bcd01d1a3c2912d5f49b",

                                null, null), null
       /*     Arrays.asList(new WarehouseExpressDeliveryConfig(//上海仓（冻品）快递售后群
            ExpressDeliveryUtil.UNKNOWN,
            1,
            "dpYLaezmVNgO3NE5iZ4EvjbOJrMqPxX6",
            "SEC0c1e7682f88bb4cb7166ecd3fe715ae005a626ef41595d04af62d069910e9d23",
            "f608f1d572bb78926f993125aaa8d84b6d49f1c5df50bcd01d1a3c2912d5f49b",null,null))*/
                ));

        WAREHOUSE_INTERCEPT_CONFIG.put(WarehouseConfEnum.DX_DP.getCode(), //广州-德信（冻品仓）
                new WarehouseConfigEntity(WarehouseConfEnum.DX_DP.getRoomTemperatureType(),//冻品
                        new WarehouseInterceptionConfig(//德信仓 （冻品）审单对接群
                                "kDnRL6jAJMDAYjEwHDvQGnjLVyMoPYe1",
                                WarehouseMsgSDConfEnum.DX_DP_SD.getSecret(),
                                WarehouseMsgSDConfEnum.DX_DP_SD.getToken(),
//                    "SEC65d0625b209020cc90739c903a5996c0769fa8e2688819ae4cfcd71e382f6317",
//            "4c3acb26d958853d57f73325e5bd449904b9addc3c12efbee8914fe7242cdab5",
                                null, null), null
          /*  Arrays.asList( new WarehouseExpressDeliveryConfig(//德信仓（冻品）快递售后群
            UNKNOWN,
            1,
            "oP0MALyR8kb9XAmOUENAM1KGJ3bzYmDO",
            "SEC65d0625b209020cc90739c903a5996c0769fa8e2688819ae4cfcd71e382f6317",
            "4c3acb26d958853d57f73325e5bd449904b9addc3c12efbee8914fe7242cdab5",null,null))*/
                ));

        WAREHOUSE_INTERCEPT_CONFIG.put(WarehouseConfEnum.JX_CW.getCode(), //江西-南昌（常温仓）
                new WarehouseConfigEntity(WarehouseConfEnum.JX_CW.getRoomTemperatureType(),//常温
                        new WarehouseInterceptionConfig(//江西仓（常温）审单对接群
                                "XPwkYGxZV3yXoPMvIEeplwMP8AgozOKL",
                                WarehouseMsgSDConfEnum.JX_CW_SD.getSecret(),
                                WarehouseMsgSDConfEnum.JX_CW_SD.getToken(),
//            "SEC6bfb84740d75d8efeaf69aeeb97747465d7c111dc7c34f90ebc7fa89d9770bb9",
//            "e6eaeec4d7e8d06c6f80849f459e2d032b938b617c22fb44246485bc6c9005bd",
                                null, null), null
            /* Arrays.asList(new WarehouseExpressDeliveryConfig(//江西仓（常温）快递售后群（圆通)
             UNKNOWN,
            1,
            "P7QG4Yx2Jp3NaeblUYkG6KBpV9dEq3XD",
            "SEC56b4084a06e60b05406b4a49ddb660e46061c21ab2282694305436c567351cb9",
            "87bf9ed52b5c60b6a340aa5cfc7c260875cf1b15a542429fe660062d2cf72bcb",null,null))*/
                ));

        WAREHOUSE_INTERCEPT_CONFIG.put(WarehouseConfEnum.CS_DP.getCode(),//长沙-中通（冻品仓）
                new WarehouseConfigEntity(WarehouseConfEnum.CS_DP.getRoomTemperatureType(),//冻品
                        new WarehouseInterceptionConfig(//长沙仓（冻品）审单对接群
                                "Obva6QBXJw6lYwAMFlx7YqoGVn4qY5Pr",
                                WarehouseMsgSDConfEnum.CS_DP_SD.getSecret(),
                                WarehouseMsgSDConfEnum.CS_DP_SD.getToken(),
//            "SEC29cb16689d420846a5b9bc319c2b33c5e0046097e9ec45ed9c255552300cee2f",
//            "8ed9de0a29deae71b5adf2cc1b2542a2ebdd1d863b0ee96c42ca948a76a5cd55",
                                null, null), null
           /* Collections.singletonList(new WarehouseExpressDeliveryConfig(//长沙仓（冻品）快递售后群（统一）
            UNKNOWN,
            1,
            "P7QG4Yx2Jp3NaeblUYkGLlNlV9dEq3XD",
            "SEC29cb16689d420846a5b9bc319c2b33c5e0046097e9ec45ed9c255552300cee2f",
            "8ed9de0a29deae71b5adf2cc1b2542a2ebdd1d863b0ee96c42ca948a76a5cd55",null,null))*/
                ));

        WAREHOUSE_INTERCEPT_CONFIG.put(WarehouseConfEnum.CS_CW.getCode(),//湖南-长沙（常温仓）
                new WarehouseConfigEntity(WarehouseConfEnum.CS_CW.getRoomTemperatureType(),//常温
                        new WarehouseInterceptionConfig(//长沙仓（常温）审单对接群
                                "YQBnd5ExVE1mZxG0TkvaBkkDVyeZqMmz",
                                WarehouseMsgSDConfEnum.CS_CW_SD.getSecret(),
                                WarehouseMsgSDConfEnum.CS_CW_SD.getToken(),
//                    "SECfde84f7f2dd69c99b6908fafb2aa5144c5db93c8177c203f956589d159eba57c",
//                    "44fa9a1f188fd78a96f8a5cb9553291344a31f1c4a1e9a68169bdd85fea9d1b4",
                                null, null), null
           /* Collections.singletonList(new WarehouseExpressDeliveryConfig(//长沙仓（常温）快递售后群（统一）
            UNKNOWN,
            1,
            "93NwLYZXWybly4ANUvY1q4G4VkyEqBQm",
            "SEC1e32020d251b1ce7fa59cef98f8ac79386f990ebc4196d60d34bd5e7f3d90008",
            "d82616b734a61bcfc6aae27b6bd5bcb70330b47f24210375b6185cd01818736d",null,null))*/
                ));

        WAREHOUSE_INTERCEPT_CONFIG.put(WarehouseConfEnum.YW_CW.getCode(), //浙江-义乌（常温仓）
                new WarehouseConfigEntity(WarehouseConfEnum.YW_CW.getRoomTemperatureType(), //常温
                        new WarehouseInterceptionConfig(//义乌仓 （常温）审单对接群
                                "kDnRL6jAJMDAYjEwHDvAPOPvVyMoPYe1",
                                WarehouseMsgSDConfEnum.YW_CW_SD.getSecret(),
                                WarehouseMsgSDConfEnum.YW_CW_SD.getToken(),
//            "SEC1e32020d251b1ce7fa59cef98f8ac79386f990ebc4196d60d34bd5e7f3d90008",
//            "d82616b734a61bcfc6aae27b6bd5bcb70330b47f24210375b6185cd01818736d",

                                null, null), null
           /* Collections.singletonList(new WarehouseExpressDeliveryConfig(//义乌仓 （常温）快递售后群（统一）
            UNKNOWN,
            1,
            "QOG9lyrgJPjOxAErIB90lvPeWzN67Mw4",
            "SEC1e32020d251b1ce7fa59cef98f8ac79386f990ebc4196d60d34bd5e7f3d90008",
            "d82616b734a61bcfc6aae27b6bd5bcb70330b47f24210375b6185cd01818736d",null,null))*/
                ));

        WAREHOUSE_INTERCEPT_CONFIG.put(WarehouseConfEnum.SY_DP.getCode(), //沈阳-天泽（冻品仓）
                new WarehouseConfigEntity(WarehouseConfEnum.SY_DP.getRoomTemperatureType(),//冻品
                        new WarehouseInterceptionConfig(//沈阳仓（冻品）审单对接群
                                "o14dA3GK8gzNMZ2YF91vgYMZJ9ekBD76",
                                WarehouseMsgSDConfEnum.SY_DP_SD.getSecret(),
                                WarehouseMsgSDConfEnum.SY_DP_SD.getToken(),
//            "SECac80969d041ff8892ac15b70fd20b4491f1756a2c3b8b2f32acff8991a2936b2",
//            "50d1f1dbd99d18a8a80998bc75ab78cd30aa96a6f9fe5db9ab0716c2f0f9aa02",
                                null, null), null
           /* Collections.singletonList(new WarehouseExpressDeliveryConfig(//沈阳仓 （冻品）快递售后群
            UNKNOWN,
            1,
            "Y1OQX0akWmlg2Z7whYaze6K28GlDd3mE",
            "SECac80969d041ff8892ac15b70fd20b4491f1756a2c3b8b2f32acff8991a2936b2",
            "50d1f1dbd99d18a8a80998bc75ab78cd30aa96a6f9fe5db9ab0716c2f0f9aa02",null,null))*/
                ));

        WAREHOUSE_INTERCEPT_CONFIG.put(WarehouseConfEnum.WH_DP.getCode(), //湖北-武汉（冻品仓）
                new WarehouseConfigEntity(WarehouseConfEnum.WH_DP.getRoomTemperatureType(), //冻品
                        new WarehouseInterceptionConfig(//湖北-武汉（冻品仓）审单对接群
                                "a9E05BDRVQNLOArKUmgZmbgpJ63zgkYA",
                                WarehouseMsgSDConfEnum.WH_DP_SD.getSecret(),
                                WarehouseMsgSDConfEnum.WH_DP_SD.getToken(),
//            "SEC4ea92f914a94e250a53386bbc52e337e5b329bacefafb4941763af706db45b66",
//            "c8b2af9667d429ca6bf44cd46487639f4f914847c842d9b9af78321e2895fa82",
                                null, null), null
           /* Collections.singletonList(new WarehouseExpressDeliveryConfig(//湖北-武汉（冻品仓）快递售后群
            UNKNOWN,
            1,
            "Y1OQX0akWmlg2Z7whYqM1A3q8GlDd3mE",
            "SEC4ea92f914a94e250a53386bbc52e337e5b329bacefafb4941763af706db45b66",
            "c8b2af9667d429ca6bf44cd46487639f4f914847c842d9b9af78321e2895fa82",null,null))*/
                ));
    }

    //同步旺店通订单数据
    @Scheduled(cron = "0 0 * * * *", zone = "Asia/Shanghai")
    public void storageScheduledTasks() {
        LocalDateTime endTime = LocalDateTime.now().minusSeconds(2);
        LocalDateTime startTime = endTime.minusHours(1);
        List<TradeQueryResponse.OrderItem> orders = findOrders(startTime, endTime, null);
        updateOrInsertItems(orders);
    }

    //    @Scheduled(cron = "0 0 9,12,16 * * ?", zone = "Asia/Shanghai")
    public void disposeScheduledTasks() {
        String sheetId = sdfYYYYMM.format(new Date());
        int currentHour = LocalDateTime.now().getHour();
        if (!Arrays.asList(9, 12, 16).contains(currentHour)) {
            return;
        }
        /**
         * 判断条件 当前时间 和最晚发货时间(－10小时内)已审核分析是否发货 没有做发货提醒
         * 揽收时间
         * 同步数据到数据库
         *
         * 实际最晚发货时间
         * 早上9点  查询时间范围 是当天9点到下午16点
         * 中午 12点   中午12点-下午17点
         * 下午 16点 去通知 16点-次日早上10点
         *
         * 早上 9点 下午 17点
         * 查询出来已发货的  物流异常提醒
         */
        List<SelfOrderDO> timeoutOrders = findTimeoutOrders(currentHour, 50);
        orderHandle(timeoutOrders, sheetId);
    }

    private void orderHandle(List<SelfOrderDO> timeoutOrders, String sheetId) {
        Map<String, List<SelfOrderDO>> WAREHOUSE_NO_ITEM = timeoutOrders.stream().filter(w -> StringUtils.isNotBlank(w.getWarehouseNo())).collect(Collectors.groupingBy(SelfOrderDO::getWarehouseNo));
        for (String warehouseNo : WAREHOUSE_NO_ITEM.keySet()) {
            List<SelfOrderDO> selfOrderDOS = WAREHOUSE_NO_ITEM.get(warehouseNo);
            //代发货 审单群
            List<SelfOrderDO> dropShipData = selfOrderDOS.stream().filter(to -> findDropshippingStatus.contains(to.getTradeStatus())).collect(Collectors.toList());
            List<String> allTradeNos = dropShipData.stream().map(SelfOrderDO::getSrcTids).collect(Collectors.toList());
//            Map<String,SelfOrderDO>DB_SRCT_IDS_ITEM=dropShipData.stream().collect(Collectors.toMap(SelfOrderDO::getSrcTids,e->e,(existing,replacement)->existing));
//            List<String>allTradeNos=new ArrayList<>(DB_SRCT_IDS_ITEM.keySet());
            List<List<String>> batchesVals = ListUtils.partition(allTradeNos, 50);
            List<TradeQueryResponse.OrderItem> allList = new ArrayList<>();
            for (int i = 0; i < batchesVals.size(); i++) {
                List<TradeQueryResponse.OrderItem> orderItems = WDTUtil.srcTidQueryOrder(String.join(",", batchesVals.get(i)), 50, 0);
                if (!orderItems.isEmpty()) {
                    allList.addAll(orderItems);
                }
            }
            Map<String, TradeQueryResponse.OrderItem> TRADE_NO_ITEM = allList.stream().collect(Collectors.toMap(TradeQueryResponse.OrderItem::getTradeNo, e -> e));
            dropShipData = dropShipData.stream().map(to -> {
                TradeQueryResponse.OrderItem orderItem = TRADE_NO_ITEM.get(to.getTradeNo());
                if (ObjectUtil.isNotNull(orderItem) && ObjectUtil.equal(to.getTradeStatus(), orderItem.getTradeStatus())) {
                    to.setTradeStatus(orderItem.getTradeStatus());
                    to.setConsignTime(toDate(orderItem.getConsignTime()));
                    to.setTradeId(orderItem.getTradeId());
                    to.setTradeNo(orderItem.getTradeNo());
                    to.setPlatformId(orderItem.getPlatformId());
                    to.setWarehouseType(orderItem.getWarehouseType());
                    to.setSrcTids(orderItem.getSrcTids());
                    to.setPayAccount(orderItem.getPayAccount());
                    to.setTradeStatus(orderItem.getTradeStatus());
                    to.setRefundStatus(orderItem.getRefundStatus());
                    to.setPayTime(toDate(orderItem.getPayTime()));
                    to.setTradeTime(toDate(orderItem.getTradeTime()));
                    to.setLogisticsNo(orderItem.getLogisticsNo());
                    to.setLogisticsName(orderItem.getLogisticsName());
                    to.setLogisticsCode(orderItem.getLogisticsCode());
                    to.setLogisticsTypeName(orderItem.getLogisticsTypeName());
                    to.setEstimateConsignTime(toDate(orderItem.getEstimateConsignTime()));
                    to.setStockoutNo(orderItem.getStockoutNo());
                    to.setWarehouseNo(warehouseNo);
                    to.setLogisticsId(orderItem.getLogisticsId());
                    selfOrderService.updateById(to);
                }
                return to;
            }).filter(to -> findDropshippingStatus.contains(to.getTradeStatus())).collect(Collectors.toList());
            //已发货  快递群
//            List<SelfOrderDO> shippedData = selfOrderDOS.stream().filter(to->findShippedStatus.contains(to.getTradeStatus())).collect(Collectors.toList());
            WarehouseConfigEntity warehouseConfigEntity = WAREHOUSE_INTERCEPT_CONFIG.get(warehouseNo);
            //审单群
            WarehouseInterceptionConfig libraryInterceptionConfig = warehouseConfigEntity.getLibraryInterceptionConfig();
            if (!dropShipData.isEmpty()) {
                List<List<String>> values = dropShipData.stream().filter(o -> ExpressDeliveryUtil.queryLogistics(o.getLogisticsNo()).getTracks().isEmpty()).map(o ->
                        Arrays.asList(o.getSrcTids(), o.getStockoutNo(), o.getTradeNo(), o.getLogisticsNo(), dateToStr(o.getEstimateConsignTime()))).collect(Collectors.toList());
                if (!values.isEmpty()) {
                    String workbookId = libraryInterceptionConfig.getWorkbookId();
                    String secret = libraryInterceptionConfig.getSecret();
                    String token = libraryInterceptionConfig.getToken();
                    List<String> atMobiles = libraryInterceptionConfig.getAtMobiles();
                    List<String> atUserIds = libraryInterceptionConfig.getAtUserIds();
                    DDUtil.updateAiExcelSendMsg(workbookId, secret, token, atMobiles, atUserIds, values, sheetId, deliveryTimeoutHeaderValues, deliveryTimeoutMsgTitle,
                            deliveryTimeoutMsgTemplate, deliveryTimeoutEndingContent, updateBatchSize);
                }
            }


            //揽收超时
      /*      List<WarehouseExpressDeliveryConfig> transitInterceptionConfigs = warehouseConfigEntity.getTransitInterceptionConfigs();
            if(ObjectUtil.isNotNull(shippedData)&&!shippedData.isEmpty()){
                //订单编号,原始单号,物流单号,最晚发货时间,发货时间
                List<List<String>> values = shippedData.stream().filter(o -> {
                    ExpressDeliveryResult result = ExpressDeliveryUtil.queryLogistics(o.getLogisticsNo());
                    return result.getSucceed() && result.getTracks().isEmpty();
                }).map(o ->
                  Arrays.asList(o.getSrcTids(), o.getStockoutNo(), o.getTradeNo(), o.getLogisticsNo(), dateToStr(o.getConsignTime()))).collect(Collectors.toList());
                if(!values.isEmpty()){
                    WarehouseExpressDeliveryConfig warehouseExpressDeliveryConfig = transitInterceptionConfigs.get(0);
                    String workbookId = warehouseExpressDeliveryConfig.getWorkbookId();
                    String secret = warehouseExpressDeliveryConfig.getSecret();
                    String token = warehouseExpressDeliveryConfig.getToken();
                    List<String> atMobiles = warehouseExpressDeliveryConfig.getAtMobiles();
                    List<String> atUserIds = warehouseExpressDeliveryConfig.getAtUserIds();
                    DDUtil.updateDocumentSending(workbookId,secret,token,atMobiles,atUserIds,values,sheetId,collectionDelayHeaderValues,collectionDelayMsgTitle,collectionDelayMsgTemplate,collectionDelayEndingContent,collectionDelayRangeAddressTemplate,updateBatchSize,dataSaveDays,timeUnit,keyTemplate);
              }
            }*/
        }
    }


    /**
     * @param startTime
     * @param endTime
     * @param findStatus
     */
    public List<TradeQueryResponse.OrderItem> findOrders(LocalDateTime startTime, LocalDateTime endTime, String findStatus) {
        List<TradeQueryResponse.OrderItem> orders = new ArrayList<>();
        String startTimeStr = FORMATTER.format(startTime);
        String endTimeStr = FORMATTER.format(endTime);

        // 1. 初始查询获取总订单数（pageSize=1足够）
        TradeQueryResponse initialResponse = WDTUtil.queryOrderList(startTimeStr, endTimeStr, findStatus, 1, 0);
        if (initialResponse == null || initialResponse.getTotalCount() == null || initialResponse.getTotalCount() == 0) {
            return orders; // 无数据时返回空列表
        }

        int totalCount = initialResponse.getTotalCount();
        int pageSize = 2000;
        if (totalCount > 0) {
//            int totalCount=total-pageSize;
//            int totalPages=(totalCount+pageSize-1) / pageSize;
//            for(int pageNo=0;pageNo<=totalPages;pageNo++){
//                stockSearch2Response = WDTUtil.stockSpecSearch2(startSearchTime, endSearchTime, pageSize, pageNo);
//                allStockDetail.addAll(stockSearch2Response.getDetailList());
//            }
        }


        int totalPages = (int) Math.ceil((double) totalCount / pageSize);
        for (int pageNo = 0; pageNo < totalPages; pageNo++) {
//            int currentPageSize = Math.min(pageSize, totalCount - (pageNo * pageSize));
            TradeQueryResponse pageResponse = WDTUtil.queryOrderList(
                    startTimeStr, endTimeStr, findStatus, pageSize, pageNo
            );

            if (pageResponse != null && pageResponse.getOrders() != null) {
                orders.addAll(pageResponse.getOrders());
            }

            // 请求间隔（避免触发限流）
            if (pageNo < totalPages - 1) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }

        orders = orders.stream().distinct().collect(Collectors.toList());

        return orders;
    }


    /**
     * @param orders
     */
    private void updateOrInsertItems(List<TradeQueryResponse.OrderItem> orders) {
        for (TradeQueryResponse.OrderItem order : orders) {
            updateOrInsertItem(order);
        }
    }

    private void updateOrInsertItem(TradeQueryResponse.OrderItem data) {
        /**
         * 0  发货后24小时未揽收=虚假发货
         * 1 揽收后24小时未更新中转=虚假揽收
         * 2 揽收后及时更新中转后24小时未更新下一条物流信息（做提醒），超48小时算丢件还会有赔付 -有揽无发
         */
//        Integer type=0;
        String consignTime = data.getConsignTime();
        String tradeNo = data.getTradeNo();
        Long tradeId = data.getTradeId();
        Integer platformId = data.getPlatformId();
        Integer warehouseType = data.getWarehouseType();
        Integer tradeStatus = data.getTradeStatus();
//        if(Arrays.asList(4,5).contains(tradeStatus)){//不要的
////          return;
//        }
        String srcTids = data.getSrcTids();
        String payAccount = data.getPayAccount();
        Integer refundStatus = data.getRefundStatus();
        String payTime = data.getPayTime();
        String tradeTime = data.getTradeTime();
        String logisticsNo = data.getLogisticsNo();
        String logisticsName = data.getLogisticsName();
        String logisticsCode = data.getLogisticsCode();
        String logisticsTypeName = data.getLogisticsTypeName();
        String estimateConsignTime = data.getEstimateConsignTime();
        String stockoutNo = data.getStockoutNo();
        Integer logisticsId = data.getLogisticsId();
        String warehouseNo = data.getWarehouseNo();
        SelfOrderDO insertItem = new SelfOrderDO();
        insertItem.setConsignTime(toDate(consignTime));
        insertItem.setTradeId(tradeId);
        insertItem.setTradeNo(tradeNo);
        insertItem.setPlatformId(platformId);
        insertItem.setWarehouseType(warehouseType);
        insertItem.setSrcTids(srcTids);
        insertItem.setPayAccount(payAccount);
        insertItem.setTradeStatus(tradeStatus);
        insertItem.setRefundStatus(refundStatus);
        insertItem.setPayTime(toDate(payTime));
        insertItem.setTradeTime(toDate(tradeTime));
        insertItem.setLogisticsNo(logisticsNo);
        insertItem.setLogisticsName(logisticsName);
        insertItem.setLogisticsCode(logisticsCode);
        insertItem.setLogisticsTypeName(logisticsTypeName);
        insertItem.setEstimateConsignTime(toDate(estimateConsignTime));
        insertItem.setStockoutNo(stockoutNo);
        insertItem.setWarehouseNo(warehouseNo);
        insertItem.setLogisticsId(logisticsId);
        if (StringUtils.isNotBlank(logisticsNo)) {
            insertItem.setLogisticsType(judgeExpressDeliveryType(logisticsNo));
        }
        SelfOrderDO oldOrder = selfOrderService.getOne(new QueryWrapper<SelfOrderDO>().eq("trade_no", tradeNo));
        List<String> srcTidss = Arrays.stream(srcTids.split(",")).distinct().collect(Collectors.toList());
        if (srcTidss.size() > 1) {
            List<Long> ids = selfOrderService.list(new QueryWrapper<SelfOrderDO>().in("src_tids", srcTidss)).stream().map(SelfOrderDO::getId).collect(Collectors.toList());
            if (!ids.isEmpty()) {
                selfOrderService.removeByIds(ids);
            }
        }
        if (ObjectUtil.isNotNull(oldOrder)) {
            String oldLogisticsNo = oldOrder.getLogisticsNo();
            if (!ObjectUtil.equal(logisticsNo, oldLogisticsNo) && !oldOrder.getIfMonitor()) {
                String latestProgress = AsyncService.setCollectionDelayStatic(insertItem);
                ExpressDeliveryUtil.trackSubSubscribe(logisticsNo);
                insertItem.setIfMonitor(true);
                insertItem.setLatestProgress(latestProgress);
            }
//        if(StringUtils.isBlank(oldOrder.getLogisticsNo())&&StringUtils.isNotBlank(logisticsNo)){
//        ExpressDeliveryResult result = ExpressDeliveryUtil.queryLogistics(oldOrder.getLogisticsNo());
//        if (result.getSucceed()){
//            List<ExpressDeliveryTrack> tracks = result.getTracks();
//            type = nextStep(tracks);
//        }
//        ExpressDeliveryUtil.trackSubSubscribe(logisticsNo);
//        }

            insertItem.setId(oldOrder.getId());
            selfOrderService.updateById(insertItem);
        } else {
            if (StringUtils.isNotBlank(logisticsNo)) {
                String latestProgress = AsyncService.setCollectionDelayStatic(insertItem);
                ExpressDeliveryUtil.trackSubSubscribe(logisticsNo);
                insertItem.setIfMonitor(true);
                insertItem.setLatestProgress(latestProgress);

            }
            selfOrderService.save(insertItem);
        }

    }


    public static Date toDate(String dateStr) {
        if (StringUtils.isBlank(dateStr)) {
            return null;
        }
        sdf.setLenient(false); // 严格模式（禁止自动转换，如 "2023-02-30" 会报错）
        try {
            return sdf.parse(dateStr);
        } catch (ParseException e) {
            return new Date(Long.parseLong(dateStr));
        }
    }

    public static String dateToStr(Date date) {
        if (ObjectUtil.isNull(date)) {
            return null;
        }
        return sdf.format(date);
    }

    /**
     *
     */
    public List<SelfOrderDO> findTimeoutOrders(Integer hour, Integer num) {
        List<String> searchTimes = findSearchTime(hour);
        List<SelfOrderDO> selfOrders = selfOrderService.findSelfOrders(searchTimes, allFindShippedStatus);
        List<String> allTradeNos = selfOrders.stream().map(SelfOrderDO::getSrcTids).collect(Collectors.toList());
        Map<String, SelfOrderDO> DB_SRCT_IDS_ITEM = selfOrders.stream().collect(Collectors.toMap(SelfOrderDO::getTradeNo, e -> e, (existing, replacement) -> existing));
//        List<String>allTradeNos=new ArrayList<>(DB_SRCT_IDS_ITEM.keySet());
        List<List<String>> batchesVals = ListUtils.partition(allTradeNos, num);
        for (int i = 0; i < batchesVals.size(); i++) {
            List<TradeQueryResponse.OrderItem> apiOrderItems = WDTUtil.srcTidQueryOrder(String.join(",", batchesVals.get(i)), num, 0);
            assert apiOrderItems != null;
            if (!apiOrderItems.isEmpty()) {
                Map<String, TradeQueryResponse.OrderItem> REQ_TRADE_NO_ITEM = apiOrderItems.stream().collect(Collectors.toMap(TradeQueryResponse.OrderItem::getTradeNo, e -> e, (existing, replacement) -> existing));
                for (String key : REQ_TRADE_NO_ITEM.keySet()) {
                    SelfOrderDO dbItem = DB_SRCT_IDS_ITEM.get(key);
                    if (ObjectUtil.isNotNull(dbItem)) {
                        TradeQueryResponse.OrderItem orderItem = REQ_TRADE_NO_ITEM.get(key);
                        dbItem.setTradeId(orderItem.getTradeId());
                        dbItem.setPlatformId(orderItem.getPlatformId());
                        dbItem.setWarehouseType(orderItem.getWarehouseType());
                        dbItem.setSrcTids(orderItem.getSrcTids());
                        dbItem.setPayAccount(orderItem.getPayAccount());
                        dbItem.setTradeStatus(orderItem.getTradeStatus());
                        dbItem.setRefundStatus(orderItem.getRefundStatus());
                        dbItem.setPayTime(toDate(orderItem.getPayTime()));
                        dbItem.setTradeTime(toDate(orderItem.getTradeTime()));
                        dbItem.setConsignTime(toDate(orderItem.getConsignTime()));
                        dbItem.setLogisticsNo(orderItem.getLogisticsNo());
                        dbItem.setLogisticsName(orderItem.getLogisticsName());
                        dbItem.setLogisticsTypeName(orderItem.getLogisticsTypeName());
                        dbItem.setEstimateConsignTime(toDate(orderItem.getEstimateConsignTime()));
                        dbItem.setStockoutNo(orderItem.getStockoutNo());
                        dbItem.setLogisticsId(orderItem.getLogisticsId());
                        dbItem.setWarehouseNo(orderItem.getWarehouseNo());
                        DB_SRCT_IDS_ITEM.put(key, dbItem);
                    }
                }
            }

        }

        List<SelfOrderDO> updateOrders = new ArrayList<>(DB_SRCT_IDS_ITEM.values());
        updateOrInsertItem(updateOrders);

        return updateOrders;
    }

    /**
     * 更新订单数据
     *
     * @param data
     */
    private void updateOrInsertItem(List<SelfOrderDO> data) {
        for (SelfOrderDO selfOrder : data) {
            selfOrderService.updateById(selfOrder);
        }
    }


    private static List<String> findSearchTime(Integer hour) {
        LocalDateTime localDateTime = LocalDateTime.now();
        LocalDateTime startDateTime = null;
        LocalDateTime endDateTime = null;
        switch (hour) {
            case 9:
                startDateTime = localDateTime.withHour(9).withSecond(0).withMinute(0);
                endDateTime = localDateTime.withHour(16).withSecond(0).withMinute(0);
                break;
            case 12:
                startDateTime = localDateTime.withHour(12).withSecond(0).withMinute(0);
                endDateTime = localDateTime.withHour(17).withSecond(0).withMinute(0);
                break;
            case 16:
                startDateTime = localDateTime.withHour(16).withSecond(0).withMinute(0);
                endDateTime = localDateTime.plusDays(1).withHour(10).withSecond(0).withMinute(0);
                break;
        }
        List<String> date = new ArrayList<>();
        assert startDateTime != null;
        date.add(startDateTime.format(FORMATTER));
        date.add(endDateTime.format(FORMATTER));
        return date;
    }

    /**
     * 获取两个LocalDateTime之间的所有整天时间字符串
     *
     * @param startDateTime 开始时间（可为null）
     * @param endDateTime   结束时间（可为null）
     * @return 时间字符串列表，格式为"yyyy-MM-dd HH:mm:ss"
     */
    public static List<String> getDailyTimeStrings(LocalDateTime startDateTime, LocalDateTime endDateTime) {
        List<String> result = new ArrayList<>();
        // 处理null情况
        if (startDateTime == null || endDateTime == null) {
            return result;
        }
        // 确保开始时间不晚于结束时间
        if (startDateTime.isAfter(endDateTime)) {
            return result;
        }
        // 检查是否为整点时间（分钟和秒都为0）
        boolean isStartWholeHour = isWholeHour(startDateTime);
        boolean isEndWholeHour = isWholeHour(endDateTime);

        // 处理开始时间（如果不是整点，直接添加）
        if (!isStartWholeHour) {
            result.add(startDateTime.format(FORMATTER));
        }

        // 计算第一个整点时间
        LocalDateTime current = startDateTime
                .withMinute(0)
                .withSecond(0)
                .withNano(0);

        if (isStartWholeHour) {
            current = startDateTime;
        } else {
            current = current.plusHours(1);
        }
        // 添加所有中间的整点时间
        while (!current.isAfter(endDateTime)) {
            // 只有当当前时间小于结束时间，或者等于结束时间且结束时间是整点时才添加
            if (current.isBefore(endDateTime) || (current.equals(endDateTime) && isEndWholeHour)) {
                result.add(current.format(FORMATTER));
            }
            current = current.plusHours(1);
        }
        // 处理结束时间（如果不是整点且未被添加过）
        if (!isEndWholeHour && !endDateTime.equals(startDateTime)) {
            result.add(endDateTime.format(FORMATTER));
        }
        return result;
    }

    /**
     * 判断时间是否为整点（分钟和秒都为0）
     */
    private static boolean isWholeHour(LocalDateTime dateTime) {
        return dateTime.getMinute() == 0 && dateTime.getSecond() == 0;
    }


}
